IOS/Android 读取蓝牙设备电量信息

IOS/Android 读取蓝牙设备电量信息

使用系统API扫描到蓝牙设备:

IOS使用到的framework
     1.CoreBluetooth/CoreBluetooth.h

Android使用到的framework
     1.android.bluetooth.BluetoothAdapter
     2.android.bluetooth.BluetoothDevice
     3.android.bluetooth.BluetoothManager

蓝牙默认广播中是不会带有电量信息的,但是可以通过定制蓝牙硬件的方式,手动添加额外信息ServiceData,然后使用IOS/Android原生的API扫描蓝牙广播数据,并根据自己定义的协议对其进行解析便可得到蓝牙电量信息。

IOS 代码示例
- ( void )centralManager:( CBCentralManager *)central didDiscoverPeripheral:( CBPeripheral *)peripheral advertisementData:( NSDictionary < NSString *, id > *)advertisementData RSSI:( NSNumber *)RSSI {
   
NSArray *keys = [advertisementData allKeys ];
   
for ( int i = 0 ; i < [keys count ]; ++i) {
       
id key = [keys objectAtIndex : i];
       
NSString *keyName = ( NSString *) key;
       
NSObject *value = [advertisementData objectForKey : key];
       
if ([value isKindOfClass : [ NSArray class ]]) {
           
printf ( "key01: %s\n" , [keyName cStringUsingEncoding : NSUTF8StringEncoding ]);
           
NSArray *values = ( NSArray *) value;
           
for ( int j = 0 ; j < [values count ]; ++j) {
               
if ([[values objectAtIndex : j] isKindOfClass : [ CBUUID class ]]) {
                   
CBUUID *uuid = [values objectAtIndex : j];
                   
NSData *data = uuid. data ;
                   
printf ( "UUID(%d):" , j);
                   
for ( int j = 0 ; j < data. length ; ++j)
                       
printf ( " %2X" , (( UInt8 *) data. bytes )[j]);
                   
printf ( "\n" );
                }
else {
                   
const char *valueString = [[value description ] cStringUsingEncoding : NSUTF8StringEncoding ];
                   
printf ( "      value(%d): %s\n" , j, valueString);
                }
            }
        }
else {
           
const char *valueString = [[value description ] cStringUsingEncoding : NSUTF8StringEncoding ];
           
           
if ([keyName isEqualToString : @"kCBAdvDataServiceData" ]) {
               
NSString *string = [ NSString stringWithUTF8String :valueString];
                [
self checkAndAddNewDevice :string];
            }
           
NSLog ( @"   key02: %s, value: %@\n" , [keyName cStringUsingEncoding : NSUTF8StringEncoding ], [ NSString stringWithUTF8String :valueString]);
        }
    }
}
// 解析广播包
- (
void )checkAndAddNewDevice:( NSString *)serverData {
   
void (^CallBack)() = ^(){
       
if ( self . delegate && [ self . delegate respondsToSelector : @selector (updateDataSources:)]) {
            [
self . delegate updateDataSources : _bleArray ];
        }
       
self . status = ( self . bleArray && self . bleArray . count > 0 ) ? BLEStatus_Gotit : BLEStatus_NoDevices ;
       
if ( self . delegate && [ self . delegate respondsToSelector : @selector (didScannerStatusChanged:)]) {
            [
self . delegate didScannerStatusChanged : _status ];
        }
    };
   
BLEModel *newModel = [ self bluetoothServerDataAnalyzer :serverData];
   
BOOL exist = false ;
   
if (! newModel) return ;
   
if (! _bleArray _bleArray = [ NSMutableArray new ];
   
for ( BLEModel *model in _bleArray ) {
       
if ([model. b_mac isEqualToString :newModel. b_mac ])
            exist =
true ;
    }
   
if (!exist) {
        [
_bleArray addObject :newModel];
        CallBack();;
    }
}

- (
BLEModel *)bluetoothServerDataAnalyzer:( NSString *)serverData {
   
BLEModel *model = nil ;
   
if (!serverData) {
       
return nil ;
    }
   
if ([serverData containsString : @" = " ] && [serverData containsString : @"<" ] && [serverData containsString : @">" ]) {
       
NSArray *array = [serverData componentsSeparatedByString : @" = " ];
       
if (array. count == 2 ) {
           
NSString *data = array[ 1 ];
            data = [data
stringByTrimmingCharactersInSet :[ NSCharacterSet whitespaceAndNewlineCharacterSet ]];
            data = [data
stringByReplacingOccurrencesOfString : @" " withString : @"" ];
           
if (data. length == 21 ) {
               
NSString *body = [data substringWithRange : NSMakeRange ( 1 , data. length - 5 )];
               
NSString *b_version = [body substringWithRange : NSMakeRange ( 0 , 2 )];
               
NSString *b_bettery = [body substringWithRange : NSMakeRange ( 2 , 2 )];
               
NSString *b_mac     = [body substringWithRange : NSMakeRange ( 4 , body. length - 4 )];
                model = [[
BLEModel alloc ] init :b_version bettery :b_bettery mac :b_mac];
//                NSLog(@" 版本 :%@ 电量 :%@ mac:%@", model.b_version, model.b_bettery, model.b_mac);
            }
        }
    }
   
return model;
}

Android 代码示例
    /**
     *
扫描设备
     *
     * @param enable
     */

   
private void scanLeDevice( boolean enable) {
       
if (enable) {
            mHandler.postDelayed(
new Runnable() {
                @Override
               
public void run() {
                   
// TODO Auto-generated method stub
                    mBluetoothAdapter.stopLeScan(mLeScanCallback);
                    invalidateOptionsMenu();
                }
            }, SCAN_PERIOD);
// 在搜索时间内,关闭搜索标志,不对搜索回调函数进行响应
            mBluetoothAdapter.startLeScan(mLeScanCallback);
        }
else {
            mBluetoothAdapter.stopLeScan(mLeScanCallback);
        }
        Logger.error(TAG,
" 是否开始扫描 =" + enable);
        invalidateOptionsMenu();
    }

   
// Device scan callback.
   
private BluetoothAdapter.LeScanCallback mLeScanCallback = new BluetoothAdapter.LeScanCallback() {
        @Override
       
public void onLeScan( final BluetoothDevice device, int rssi, byte [] scanRecord) {
           
final IBeaconClass.IBeacon ibeacon = IBeaconClass.fromScanData(device, rssi, scanRecord);
           
if (ibeacon == null ) return ;
           
try {
                String strTemp = StringUtil.bytesToHexString(scanRecord);
                Logger.error(TAG, strTemp.length() +
"= 长度,回调方法 -onLeScan()=" + strTemp); //0201061aff4c000215fda50693a4e24fb1afcfc6eb07647825000a0007c5090942523531343633310b1642523d6400cdff003ab100000000000000000000
               
if (!TextUtils.isEmpty(strTemp)) {
                    String usefulData = strTemp.substring(
86 , 106 ); //4252 3d6400cdff003a9e
                    Logger.error(TAG, usefulData.length() +
"= 长度,回调方法 -onLeScan() 截取有用数据 usefulData=" + usefulData);
//                String serviceID1 = usefulData.substring(2);
//                    String serviceID = usefulData.substring(2, 4);
//                    if (serviceID.equals("52")) {
                        String strVersion = usefulData.substring(
4 , 6 );
                       
int intVersion = Integer.parseInt(strVersion, 16 );
                        String strPower = usefulData.substring(
6 , 8 );
                       
int intPower = Integer.parseInt(strPower, 16 );
                        Logger.error(TAG, strVersion +
"=strVersion 回调方法 -onLeScan() ,版本值 intVersion=" + intVersion);
                        Logger.error(TAG, strPower +
"=strPower 回调方法 -onLeScan() ,电量值 intPower=" + intPower);
                       
if (intPower > 0 ) {
                            ibeacon.version = intVersion;
                            ibeacon.power = intPower;
                            runOnUiThread(
new Runnable() {
                                @Override
                               
public void run() {
                                    adapter.addDevice(ibeacon);
                                }
                            });

                        }
//                    }
                }
            }
catch (Exception e) {
                Logger.error(TAG,
" 解析蓝牙数据出错 =" + e);
            }
        }
    };





你可能感兴趣的:(Android应用开发,IOS应用开发)