【问题标题】:How can I use semaphore to do a correct android ble communication?如何使用信号量进行正确的 android ble 通信?
【发布时间】:2015-06-17 07:09:34
【问题描述】:

我对来自我的 Android 应用和一个外围设备的 ble 通信存在疑问。该外围设备通过通知某个特征“A”发送数据,我可以在其上写入另一个特定特征“B”。 为此,我这样做:

   Semaphore sem = new Semaphore(1);
   void notifyActivation()
    {bluetoothGatt.setCharacteristicNotification(characteristic, true);

    BluetoothGattDescriptor descriptor = characteristic.getDescriptor(
            UUID.fromString("00002902-0000-1000-8000-00805f9b34fb"));
    if(descriptor != null )
    {

        try 
        {
            sem.acquire();
        } 
        catch (InterruptedException e) 
        {
            e.printStackTrace();
        }

        Log.i("debug","scrittura descrittore");
        descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
        bluetoothGatt.writeDescriptor(descriptor);
    }
 }

@Override
public void onDescriptorWrite(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) 
                {
                    super.onDescriptorWrite(gatt, descriptor, status);
                    Log.i("debug", "descriptor status: "+status);

                    sem.release();
                }


public void write(final BluetoothGattCharacteristic characteristic)
{

    new Thread(new Runnable() {

        @Override
        public void run() {

            try {
                //acquisisco il semaforo se è libero se no mi blocco
                sem.acquire();
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
    boolean res=bluetoothGatt.writeCharacteristic(characteristic);

    if(!res)
    {
        Log.i("debug","scrittura fallita");
        //res=bluetoothGatt.writeCharacteristic(characteristic);
    }
    sem.release();

        }
    }).start();
}

我使用了信号量,因为如果我在调用 ondescriptorwrite 之前进行写入,写入会失败,但我想知道这样我是否会丢失一些通知。..

信号量的使用方式正确吗?或者它会给我带来一些问题?

【问题讨论】:

    标签: android bluetooth-lowenergy semaphore java.util.concurrent android-ble


    【解决方案1】:

    我认为您的信号量模式可以工作。但是如果你这样做,你应该设置一个超时来清除信号量,以防你永远得不到响应。这当然是可能的,因为设备可能已经超出范围或断电(甚至崩溃)。

    另一种可能性是使用命令设计模式并创建一个命令队列,以便在有多个命令时对命令进行排队。

    【讨论】:

    • 嗨!谢谢 !我没有想到这个问题,我可以通过什么方式实现这个超时?你有什么建议吗? :)
    • 如果我这样做:“boolean p= sem.tryAcquire(5000); if (p == false) sem.release()” ?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-02-10
    • 1970-01-01
    • 2021-01-17
    • 1970-01-01
    • 2012-10-07
    • 2011-02-07
    • 1970-01-01
    相关资源
    最近更新 更多