Я работаю над приложением BLE для Android.
Существует ли какая-либо процедура для одновременного подключения нескольких устройств BLE (создания нескольких подключений) в Android. Поскольку в моем приложении есть несколько источников света BLE, поэтому первый источник света успешно подключается, когда я нажимаю, чтобы подключиться ко второму источнику света, второй источник света также подключается. но через некоторое время второй свет автоматически отключается. Мне нужно подключить максимум 8 источников света.
Вот что я делаю
private final BluetoothGattCallback mGattCallback = new BluetoothGattCallback()
{
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status,
int newState)
{
String intentAction;
if (newState == BluetoothProfile.STATE_CONNECTED)
{
intentAction = GattActions.ACTION_GATT_CONNECTED;
broadcastUpdate(intentAction);
Log.i(DSERVICE_TAG, "Connected to GATT server.");
// Attempts to discover services after successful connection.
Log.i(DSERVICE_TAG, "Attempting to start service discovery:"
+ mBluetoothGatt.discoverServices());
readRssi();
}
else if (newState == BluetoothProfile.STATE_DISCONNECTED)
{
intentAction = GattActions.ACTION_GATT_DISCONNECTED;
Log.i(DSERVICE_TAG, "Disconnected from GATT server.");
broadcastUpdate(intentAction);
}
}
public void onReadRemoteRssi(BluetoothGatt gatt, int rssi, int status)
{
if (status == BluetoothGatt.GATT_SUCCESS)
{
broadcastUpdate(GattActions.ACTION_GATT_RSSI, rssi);
}
else
{
Log.w(DSERVICE_TAG, "onReadRemoteRssi received: " + status);
}
}
@Override
public void onServicesDiscovered(BluetoothGatt gatt, int status)
{
if (status == BluetoothGatt.GATT_SUCCESS)
{
Log.v(DSERVICE_TAG, "Device Discovered Uuids Are==" + gatt.getDevice().getUuids());
broadcastUpdate(GattActions.ACTION_GATT_SERVICES_DISCOVERED);
}
else
{
Log.w(DSERVICE_TAG, "onServicesDiscovered received: " + status);
}
}
@Override
public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status)
{
if (status == BluetoothGatt.GATT_SUCCESS)
{
Log.d("TestCharacter", "onCharacteristicRead character " + characteristic.getUuid());
broadcastUpdate(GattActions.ACTION_DATA_AVAILABLE, characteristic);
broadcastUpdate(GattActions.EXTRA_DATA, characteristic);
filterCharacteristicOfDevices(gatt, characteristic);
}
}
@Override
public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status)
{
//super.onCharacteristicWrite(gatt, characteristic, status);
if (status != BluetoothGatt.GATT_SUCCESS)
{
try
{
Thread.sleep(100);
}
catch (InterruptedException e)
{
}
writeCharacteristic(characteristic, gatt);
}
}
И характеристики чтения и readRss()
public void readCharacteristic(BluetoothGattCharacteristic characteristic)
{
if (mBluetoothAdapter == null || mBluetoothGatt == null)
{
Log.w(DSERVICE_TAG, "BluetoothAdapter not initialized");
return;
}
mBluetoothGatt.readCharacteristic(characteristic);
try
{
Thread.sleep(100);
}
catch (InterruptedException e)
{
}
}
public void readRssi()
{
if (mBluetoothAdapter == null || mBluetoothGatt == null)
{
Log.w(DSERVICE_TAG, "BluetoothAdapter not initialized");
return;
}
mBluetoothGatt.readRemoteRssi();
new Handler().postDelayed(readRssi, 200);
}
private Runnable readRssi = new Runnable()
{
@Override
public void run()
{
//read remote rssi every second
for (Map.Entry entryGatt : myApplication.deviceGattMap.entrySet())
{
String deviceAddress = entryGatt.getKey();
BluetoothGatt bluetothGatt = entryGatt.getValue();
bluetothGatt.readRemoteRssi();
//delay for reading rssi
try
{
Thread.sleep(200);
}
catch (InterruptedException e)
{
}
}
}
};
и метод подключения, в котором я добавляю объект GATT в HashMap для каждого источника света: -
public boolean connect(final String address)
{
if (mBluetoothAdapter == null || address == null)
{
Log.w(DSERVICE_TAG,
"BluetoothAdapter not initialized or unspecified address.");
return false;
}
// Previously connected device. Try to reconnect.
if (mBluetoothDeviceAddress != null
&& address.equals(mBluetoothDeviceAddress)
&& mBluetoothGatt != null)
{
Log.d(DSERVICE_TAG,
"Trying to use an existing mBluetoothGatt for connection.");
if (mBluetoothGatt.connect())
{
return true;
}
else
{
return false;
}
}
final BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
if (device == null)
{
Log.w(DSERVICE_TAG, "Device not found. Unable to connect.");
return false;
}
// We want to directly connect to the device, so we are setting the
// autoConnect
// parameter to false.
mBluetoothGatt = device.connectGatt(this, false, mGattCallback);
Log.d(DSERVICE_TAG, "Trying to create a new connection.");
mBluetoothDeviceAddress = address;
//Arun
//delay for reading rssi
try
{
Thread.sleep(100);
}
catch (InterruptedException e)
{
}
//map of gatt
myApplication.deviceGattMap.put(mBluetoothDeviceAddress, mBluetoothGatt);
try
{
Thread.sleep(50);
}
catch (InterruptedException e)
{
}
Log.d(DSERVICE_TAG, "GATTMAP SIZE=="+ myApplication.deviceGattMap.size()+"---"+myApplication.deviceGattMap.get(mBluetoothDeviceAddress));
return true;
}
Подробнее здесь: https://stackoverflow.com/questions/319 ... low-energy
Как создать несколько соединений одновременно в Android Bluetooth с низким энергопотреблением (BLE)? ⇐ Android
Форум для тех, кто программирует под Android
1766981045
Anonymous
Я работаю над приложением BLE для Android.
Существует ли какая-либо процедура для одновременного подключения нескольких [b]устройств BLE[/b] (создания нескольких подключений) в Android. Поскольку в моем приложении есть несколько источников света BLE, поэтому первый источник света успешно подключается, когда я нажимаю, чтобы подключиться ко второму источнику света, второй источник света также подключается. но через некоторое время второй свет автоматически отключается. Мне нужно подключить максимум 8 источников света.
Вот что я делаю
private final BluetoothGattCallback mGattCallback = new BluetoothGattCallback()
{
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status,
int newState)
{
String intentAction;
if (newState == BluetoothProfile.STATE_CONNECTED)
{
intentAction = GattActions.ACTION_GATT_CONNECTED;
broadcastUpdate(intentAction);
Log.i(DSERVICE_TAG, "Connected to GATT server.");
// Attempts to discover services after successful connection.
Log.i(DSERVICE_TAG, "Attempting to start service discovery:"
+ mBluetoothGatt.discoverServices());
readRssi();
}
else if (newState == BluetoothProfile.STATE_DISCONNECTED)
{
intentAction = GattActions.ACTION_GATT_DISCONNECTED;
Log.i(DSERVICE_TAG, "Disconnected from GATT server.");
broadcastUpdate(intentAction);
}
}
public void onReadRemoteRssi(BluetoothGatt gatt, int rssi, int status)
{
if (status == BluetoothGatt.GATT_SUCCESS)
{
broadcastUpdate(GattActions.ACTION_GATT_RSSI, rssi);
}
else
{
Log.w(DSERVICE_TAG, "onReadRemoteRssi received: " + status);
}
}
@Override
public void onServicesDiscovered(BluetoothGatt gatt, int status)
{
if (status == BluetoothGatt.GATT_SUCCESS)
{
Log.v(DSERVICE_TAG, "Device Discovered Uuids Are==" + gatt.getDevice().getUuids());
broadcastUpdate(GattActions.ACTION_GATT_SERVICES_DISCOVERED);
}
else
{
Log.w(DSERVICE_TAG, "onServicesDiscovered received: " + status);
}
}
@Override
public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status)
{
if (status == BluetoothGatt.GATT_SUCCESS)
{
Log.d("TestCharacter", "onCharacteristicRead character " + characteristic.getUuid());
broadcastUpdate(GattActions.ACTION_DATA_AVAILABLE, characteristic);
broadcastUpdate(GattActions.EXTRA_DATA, characteristic);
filterCharacteristicOfDevices(gatt, characteristic);
}
}
@Override
public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status)
{
//super.onCharacteristicWrite(gatt, characteristic, status);
if (status != BluetoothGatt.GATT_SUCCESS)
{
try
{
Thread.sleep(100);
}
catch (InterruptedException e)
{
}
writeCharacteristic(characteristic, gatt);
}
}
И характеристики чтения и readRss()
public void readCharacteristic(BluetoothGattCharacteristic characteristic)
{
if (mBluetoothAdapter == null || mBluetoothGatt == null)
{
Log.w(DSERVICE_TAG, "BluetoothAdapter not initialized");
return;
}
mBluetoothGatt.readCharacteristic(characteristic);
try
{
Thread.sleep(100);
}
catch (InterruptedException e)
{
}
}
public void readRssi()
{
if (mBluetoothAdapter == null || mBluetoothGatt == null)
{
Log.w(DSERVICE_TAG, "BluetoothAdapter not initialized");
return;
}
mBluetoothGatt.readRemoteRssi();
new Handler().postDelayed(readRssi, 200);
}
private Runnable readRssi = new Runnable()
{
@Override
public void run()
{
//read remote rssi every second
for (Map.Entry entryGatt : myApplication.deviceGattMap.entrySet())
{
String deviceAddress = entryGatt.getKey();
BluetoothGatt bluetothGatt = entryGatt.getValue();
bluetothGatt.readRemoteRssi();
//delay for reading rssi
try
{
Thread.sleep(200);
}
catch (InterruptedException e)
{
}
}
}
};
и метод подключения, в котором я добавляю объект GATT в HashMap для каждого источника света: -
public boolean connect(final String address)
{
if (mBluetoothAdapter == null || address == null)
{
Log.w(DSERVICE_TAG,
"BluetoothAdapter not initialized or unspecified address.");
return false;
}
// Previously connected device. Try to reconnect.
if (mBluetoothDeviceAddress != null
&& address.equals(mBluetoothDeviceAddress)
&& mBluetoothGatt != null)
{
Log.d(DSERVICE_TAG,
"Trying to use an existing mBluetoothGatt for connection.");
if (mBluetoothGatt.connect())
{
return true;
}
else
{
return false;
}
}
final BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
if (device == null)
{
Log.w(DSERVICE_TAG, "Device not found. Unable to connect.");
return false;
}
// We want to directly connect to the device, so we are setting the
// autoConnect
// parameter to false.
mBluetoothGatt = device.connectGatt(this, false, mGattCallback);
Log.d(DSERVICE_TAG, "Trying to create a new connection.");
mBluetoothDeviceAddress = address;
//Arun
//delay for reading rssi
try
{
Thread.sleep(100);
}
catch (InterruptedException e)
{
}
//map of gatt
myApplication.deviceGattMap.put(mBluetoothDeviceAddress, mBluetoothGatt);
try
{
Thread.sleep(50);
}
catch (InterruptedException e)
{
}
Log.d(DSERVICE_TAG, "GATTMAP SIZE=="+ myApplication.deviceGattMap.size()+"---"+myApplication.deviceGattMap.get(mBluetoothDeviceAddress));
return true;
}
Подробнее здесь: [url]https://stackoverflow.com/questions/31956117/how-to-create-multiple-connection-at-same-time-in-android-bluetooth-low-energy[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия