您的位置:首页 > 移动开发 > Android开发

医疗设备BLE蓝牙开发的总结。

2015-05-21 13:54 387 查看
各种概念请参考:   官方版 https://developer.android.com/guide/topics/connectivity/bluetooth-le.html  中文版  http://blog.csdn.net/qinxiandiqi/article/details/40741269   中文版有官方demo 的解析 以下以另一个demo 为例子 这个demo 的github网址是:  https://github.com/movisens/SmartGattLib   关于 Service :   每一个设备 包含有 多个Services  每个service 对应一个uuid(可以根据Assign Number     生成,后面会提到), services 的 uuid 在attribute添加 就是在官方SmartGattLib 的
  Characteristic(与以下的characteristic不同,这个只是作者这样命名)这个类里面。
     关于Characteristic:   每一个Service 包含多个Characteristic, 每一个  Characteristic:对应一个uuid(可以根据Assign Number   生成,后面会提到)),Characteristic uuid 在attribute 添加 就是在  SmartGattLib的Characteristic(与标题的characteristic不同,这个只是作者这样命名)这个类里面。   1  如何获得想要的数据?   我们想要的数据是包含在每一个Characteristic , 那怎么知道哪一部分数据代表哪些值  呢? 在蓝牙的官网也可以找到  https://developer.bluetooth.org/gatt/characteristics/Pages/CharacteristicsHome.aspx   以的 HeartRateMeasurement 为例  点开以上网址中的 Heart Rate  Measurement (也可以下载他的xml 格式),先看Smartlib 里面HeartRateMeasurement  这个类,hrmval 代表心率的值
  public HeartRateMeasurement(byte[] value) {
   GattByteBuffer bb = GattByteBuffer.wrap(value);
   byte flags = bb.getInt8();
   if (isHeartRateInUINT16(flags)) {
      hrmval = bb.getUint16();//为什么是Unit16 看下图BitField 里的 definition
   } else {
      hrmval = bb.getUint8();
   }
}
  isHeartRateInUINT16(flags))的 方法是这样子的
private boolean isHeartRateInUINT16(byte flags) {
   if ((flags & GattUtils.FIRST_BITMASK) != 0)
      return true;
   return false;
}
First_BITMASK 代表的就是 下图中 bit 那一栏的0 第一个 以此类推
   这样就获得了 心率的值。 2  如何获得每个Service 和 Characteristic的uuid ?   先看下图,刚刚打开的HeartRateMeasurement 页面标题的下方,有一个assigned Number:    每一个service 和 characteristic在蓝牙的官网里面都有一个assgined Number(当然厂商也会提供,不过不用担心不一样,官网里的是行业标准,厂商提供的大部分assignednumber 会和官网相同,只有少数厂商自定义的Service 和Characteristic 会不   一样,这时候就要找厂商索要)   Service assigned number url :https://developer.bluetooth.org/gatt/services/Pages/ServicesHome.aspx   Characteristic assigned number url :https://developer.bluetooth.org/gatt/characteristics/Pages/CharacteristicsHome.aspx在SmartGattLib的GattUtils 有一个这样的方法,
    public static UUID toUuid(long assignedNumber) {
    return new UUID((assignedNumber << 32) | 0x1000, leastSigBits);
    }
这样就可以根据assigned number 生成UUID不过记住要把它转成long 类型的 0x2A37 要变成0x2A37L,
 其中 leastSigBits =0x800000805f9b34fbL
为什么是这个值呢? 为什么 assigned number 只有16bits长呢,UUID 不是128位吗?
原来Bluetooth 将UUID 的其他部份固定,只取16bits 作为各种Service 的区分,这昂可以节省分析SDP Record 的时间 and 程序空间,避免增加蓝牙设备的成本。
BASE UUID 是 0000xxxx-0000-1000-8000-00805F9B34FB,只要把xxxx 换为 assigned number 就得 到UUID,详情可以参考
Protocols UUID http://www.bluetooth.org/Technical/AssignedNumbers/service_discovery.htm 
其他部分看方sample 应该就可以搞明白。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息