草庐IT

关于android:无法从BLE设备读取特征值

codeneng 2023-03-28 原文

Not able to read a characteristic value from BLE device

我需要向 Android BLE 设备写入和读取特征值。我能写但不能读。这是我的写作方式:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public void writeCustomCharacteristic(int value) {
    if (mBluetoothAdapter == null || mBluetoothGatt == null) {
        Log.w(TAG,"BluetoothAdapter not initialized");
        return;
    }
    /*check if the service is available on the device*/
    BluetoothGattService mCustomService = mBluetoothGatt.getService(UUID.fromString("<MY SERVICE UUID>"));
    if(mCustomService == null){
        Log.w(TAG,"Custom BLE Service not found");
        return;
    }
    /*get the read characteristic from the service*/
    BluetoothGattCharacteristic mWriteCharacteristic = mCustomService.getCharacteristic(UUID.fromString("<MY CHARACTERSTIC UUID>"));
   mWriteCharacteristic.setWriteType(BluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE);
       mWriteCharacteristic.setValue(value,BluetoothGattCharacteristic.FORMAT_UINT8,0);
    if(!mBluetoothGatt.writeCharacteristic(mWriteCharacteristic)){
        Log.w(TAG,"Failed to write characteristic");
    }else{
        Log.w(TAG,"Success to write characteristic");
    }
}

如果我使用

这个操作是成功的

1
 mWriteCharacteristic.setWriteType(BluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE);

如果我使用任何其他写入类型而不是 WRITE_TYPE_NO_RESPONSE 那么它不会触发 onCharacteristicWrite() 回调方法。

这是我阅读特征的方式:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
 private boolean readCharacteristics(int groupPosition,int childPosition){
    try{
        if (mGattCharacteristics != null) {
            final BluetoothGattCharacteristic characteristic = mGattCharacteristics.get(2).get(2);
            final int charaProp = characteristic.getProperties();
            if ((charaProp | BluetoothGattCharacteristic.PROPERTY_READ) > 0) {
                // If there is an active notification on a characteristic, clear
                // it first so it doesn't update the data field on the user interface.
                if (mNotifyCharacteristic != null) {
                    mBluetoothLeService.setCharacteristicNotification(mNotifyCharacteristic, false);
                    mNotifyCharacteristic = null;
                }
                mBluetoothLeService.readCharacteristic(characteristic);
            }
            if ((charaProp | BluetoothGattCharacteristic.PROPERTY_NOTIFY) > 0) {
                mNotifyCharacteristic = characteristic;
                mBluetoothLeService.setCharacteristicNotification(characteristic, true);
            }
            waitSometime(100);
            if ((charaProp | BluetoothGattCharacteristic.PROPERTY_INDICATE) > 0) {
                mNotifyCharacteristic = characteristic;
                mBluetoothLeService.setCharacteristicIndication(characteristic, true);
            }
            waitSometime(100);
            if ((charaProp | BluetoothGattCharacteristic.PROPERTY_WRITE) > 0) {

                byte[] value = characteristic.getValue(); //this is being NULL always

                if (mNotifyCharacteristic != null) {
                    mBluetoothLeService.setCharacteristicNotification(mNotifyCharacteristic, true);
                    mNotifyCharacteristic = null;
                }
                mBluetoothLeService.writeCharacteristic(characteristic, value);
                if(value!=null&&value.length>0) {
                    Toast.makeText(DeviceControlActivity.this,"success reading data",Toast.LENGTH_LONG).show();
                }else{
                  Toast.makeText(DeviceControlActivity.this,"error reading data",Toast.LENGTH_LONG).show();
                }
            }
       /* if ((charaProp | BluetoothGattCharacteristic.PROPERTY_INDICATE) > 0) {
            mNotifyCharacteristic = characteristic;
            //characteristic.setWriteType();
            mBluetoothLeService.setCharacteristicIndication(
                    characteristic, true);
            byte[] value=characteristic.getValue();
        }*/
            return true;
        }
    }catch (Exception e){
        e.printStackTrace();
    }
    return false;
}

characteristic.getValue() 始终返回 null。我哪里错了?

  • 您错误地使用了 bitor 而不是 bitand。另外,不要睡觉,然后期望该值已被读取。而是等待通知读取何时完成的回调。


这是我的看法:

你需要弄清楚你将获得什么样的特征数据?其中一些需要先设置指示或通知!喜欢:

一个。获取特征的描述符

1
2
   BluetoothGattDescriptor descriptor = gattCharacteristic.getDescriptors().get(0);
     //Usually is Client_Characteristic_Configuration

乙。根据特性,设置描述符的property()为true。

1
2
3
4
5
6
7
8
9
10
if ((gattCharacteristic.PROPERTY_NOTIFY)> 0 ){
    if (descriptor != null) {
       descriptor.setValue((BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE));
       }
   }
else if((gattCharacteristic.PROPERTY_INDICATE) >0 ){
    if(descriptor != null){
       descriptor.setValue(BluetoothGattDescriptor.ENABLE_INDICATION_VALUE);
       }
   }

c。将值发送到远程 BLE 设备。

1
gatt.writeDescriptor(descriptor);

之后,你可以在回调函数中获取数据:

1
onCharacteristicChanged

至少以上对我有用!
希望能帮到人~

  • 你救了我的命

有关关于android:无法从BLE设备读取特征值的更多相关文章

  1. ruby-on-rails - 由于 "wkhtmltopdf",PDFKIT 显然无法正常工作 - 2

    我在从html页面生成PDF时遇到问题。我正在使用PDFkit。在安装它的过程中,我注意到我需要wkhtmltopdf。所以我也安装了它。我做了PDFkit的文档所说的一切......现在我在尝试加载PDF时遇到了这个错误。这里是错误:commandfailed:"/usr/local/bin/wkhtmltopdf""--margin-right""0.75in""--page-size""Letter""--margin-top""0.75in""--margin-bottom""0.75in""--encoding""UTF-8""--margin-left""0.75in""-

  2. ruby - 如何将脚本文件的末尾读取为数据文件(Perl 或任何其他语言) - 2

    我正在寻找执行以下操作的正确语法(在Perl、Shell或Ruby中):#variabletoaccessthedatalinesappendedasafileEND_OF_SCRIPT_MARKERrawdatastartshereanditcontinues. 最佳答案 Perl用__DATA__做这个:#!/usr/bin/perlusestrict;usewarnings;while(){print;}__DATA__Texttoprintgoeshere 关于ruby-如何将脚

  3. ruby-on-rails - 无法使用 Rails 3.2 创建插件? - 2

    我对最新版本的Rails有疑问。我创建了一个新应用程序(railsnewMyProject),但我没有脚本/生成,只有脚本/rails,当我输入ruby./script/railsgeneratepluginmy_plugin"Couldnotfindgeneratorplugin.".你知道如何生成插件模板吗?没有这个命令可以创建插件吗?PS:我正在使用Rails3.2.1和ruby​​1.8.7[universal-darwin11.0] 最佳答案 随着Rails3.2.0的发布,插件生成器已经被移除。查看变更日志here.现在

  4. ruby - 无法运行 Rails 2.x 应用程序 - 2

    我尝试运行2.x应用程序。我使用rvm并为此应用程序设置其他版本的ruby​​:$rvmuseree-1.8.7-head我尝试运行服务器,然后出现很多错误:$script/serverNOTE:Gem.source_indexisdeprecated,useSpecification.Itwillberemovedonorafter2011-11-01.Gem.source_indexcalledfrom/Users/serg/rails_projects_terminal/work_proj/spohelp/config/../vendor/rails/railties/lib/r

  5. ruby-on-rails - 无法在centos上安装therubyracer(V8和GCC出错) - 2

    我正在尝试在我的centos服务器上安装therubyracer,但遇到了麻烦。$geminstalltherubyracerBuildingnativeextensions.Thiscouldtakeawhile...ERROR:Errorinstallingtherubyracer:ERROR:Failedtobuildgemnativeextension./usr/local/rvm/rubies/ruby-1.9.3-p125/bin/rubyextconf.rbcheckingformain()in-lpthread...yescheckingforv8.h...no***e

  6. Ruby 写入和读取对象到文件 - 2

    好的,所以我的目标是轻松地将一些数据保存到磁盘以备后用。您如何简单地写入然后读取一个对象?所以如果我有一个简单的类classCattr_accessor:a,:bdefinitialize(a,b)@a,@b=a,bendend所以如果我从中非常快地制作一个objobj=C.new("foo","bar")#justgaveitsomerandomvalues然后我可以把它变成一个kindaidstring=obj.to_s#whichreturns""我终于可以将此字符串打印到文件或其他内容中。我的问题是,我该如何再次将这个id变回一个对象?我知道我可以自己挑选信息并制作一个接受该信

  7. ruby - 无法让 RSpec 工作—— 'require' : cannot load such file - 2

    我花了三天的时间用头撞墙,试图弄清楚为什么简单的“rake”不能通过我的规范文件。如果您遇到这种情况:任何文件夹路径中都不要有空格!。严重地。事实上,从现在开始,您命名的任何内容都没有空格。这是我的控制台输出:(在/Users/*****/Desktop/LearningRuby/learn_ruby)$rake/Users/*******/Desktop/LearningRuby/learn_ruby/00_hello/hello_spec.rb:116:in`require':cannotloadsuchfile--hello(LoadError) 最佳

  8. ruby - 无法覆盖 irb 中的 to_s - 2

    我在pry中定义了一个函数:to_s,但我无法调用它。这个方法去哪里了,怎么调用?pry(main)>defto_spry(main)*'hello'pry(main)*endpry(main)>to_s=>"main"我的ruby版本是2.1.2看了一些答案和搜索后,我认为我得到了正确的答案:这个方法用在什么地方?在irb或pry中定义方法时,会转到Object.instance_methods[1]pry(main)>defto_s[1]pry(main)*'hello'[1]pry(main)*end=>:to_s[2]pry(main)>defhello[2]pry(main)

  9. ruby - 如何根据特征实现 FactoryGirl 的条件行为 - 2

    我有一个用户工厂。我希望默认情况下确认用户。但是鉴于unconfirmed特征,我不希望它们被确认。虽然我有一个基于实现细节而不是抽象的工作实现,但我想知道如何正确地做到这一点。factory:userdoafter(:create)do|user,evaluator|#unwantedimplementationdetailshereunlessFactoryGirl.factories[:user].defined_traits.map(&:name).include?(:unconfirmed)user.confirm!endendtrait:unconfirmeddoenden

  10. ruby - 无法在 60 秒内获得稳定的 Firefox 连接 (127.0.0.1 :7055) - 2

    我使用的是Firefox版本36.0.1和Selenium-Webdrivergem版本2.45.0。我能够创建Firefox实例,但无法使用脚本继续进行进一步的操作无法在60秒内获得稳定的Firefox连接(127.0.0.1:7055)错误。有人能帮帮我吗? 最佳答案 我遇到了同样的问题。降级到firefoxv33后一切正常。您可以找到旧版本here 关于ruby-无法在60秒内获得稳定的Firefox连接(127.0.0.1:7055),我们在StackOverflow上找到一个类

随机推荐