iOS从蓝牙4.2 BLE设备读取数据

时间:2016-02-04 06:59:10

标签: ios bluetooth

我正在尝试从BLE设备读取数据,从委托方法获取数据 - (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error

我正在使用属性value从CBCharacteristic对象中读取数据。

这将返回NSData。 我将此NSData转换为字节。

如何根据此字节数据计算权重?通过这段代码,我得不到确切的价值。

这是MyCode

/** This callback lets us know more data has arrived via notification on the characteristic
 */
- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
{


    NSLog(@"peripheral %@", peripheral);
    NSLog(@"chacteristic %@", characteristic);
    NSLog(@"chacteristic value %@", [characteristic value]);

    Response Is Like This
    peripheral <CBPeripheral: 0x15e469e90, identifier = A4B7E3A0-A988-02CF-3FAE-3B62056F465B, name = eBody-Fat-Scale, state = connected>

    chacteristic <CBCharacteristic: 0x15e250980, UUID = 2A9D, properties = 0x20, value = <0ee803df 07010116 390901ff ff0000>, notifying = YES>

    chacteristic value <0ee803df 07010116 390901ff ff0000>



    if (error) {
        NSLog(@"Error discovering characteristics: %@ and %@", [error localizedDescription],[error localizedFailureReason]);
        return;
    }

    int height;

    self.targetPeripheral = peripheral;
    NSData *tempData=characteristic.value;

    NSString *stringFromData = [[NSString alloc] initWithData:characteristic.value encoding:NSUTF8StringEncoding];
    NSString *str = [NSString stringWithUTF8String:[tempData bytes]];
    NSLog(@"string data %@",str);
    NSData *lol = characteristic.value;

    NSLog(@"length %lu", (unsigned long)[lol length]);
    Byte *byte = (Byte *)[lol bytes];
    for(int i = 0;i<[lol length];i++)
    {
        NSLog(@"Receive byte:%d",byte[i]);
    }

   /* self.targetPeripheral = peripheral;

    NSString *stringFromData = [[NSString alloc] initWithData:characteristic.value encoding:NSUTF8StringEncoding];

    NSData *lol = characteristic.value;
    Byte *byte = (Byte *)[lol bytes];
    for(int i = 0;i<[lol length];i++)
    {
        NSLog(@"Received bytes:%d",byte[i]);
    }*/


    if(byte[0] == 0xfc)
    {
        Byte weightHigh = 0;
        if(byte[1] >= 0xc0)
        {
            weightHigh = byte[1] - 0xc0;
        }
        else if(byte[1] >= 0x80)
        {
            weightHigh = byte[1] - 0x80;
        }
        else if(byte[1]>= 0x40)
        {
            weightHigh = byte[1] - 0x40;
        }

        float weightdata = (float)(weightHigh * 256 + byte[2])/10;
        NSUserDefaults *prefers = [NSUserDefaults standardUserDefaults];

        if([[prefers objectForKey:@"units"] isEqualToString:@"ft"])
        {
            NSString *weight = [[NSString alloc]initWithFormat:@"%.1f",[UnitParse convertKgToLb:weightdata]];
            _weightDataLabel.text = [[NSString alloc] initWithFormat:@"%@",weight];

        }
        else
        {
            NSString *weight = [[NSString alloc]initWithFormat:@"%.1f",weightdata];
            _weightDataLabel.text = [[NSString alloc] initWithFormat:@"%@",weight];
        }

        if(weightdata != _lastWeightData)
        {
            [RCCircleAnimation stopAnimation:_circleImageView.layer];
            _lastWeightData = weightdata;

            if(weightHigh * 256 + byte[2] == 0x3f*256+255)//overload
            {
                _weightDataLabel.text = @"overload";
            }
            else
            {
                NSThread* myThread1 = [[NSThread alloc] initWithTarget:self selector:@selector(mySoundPlayer)object:nil];
                [myThread1 start];

                NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
                [dic setObject:[[NSString alloc] initWithFormat:@"%2f",weightdata] forKey:@"Weight"];
                NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
                [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
                NSString *datestr = [formatter stringFromDate:[NSDate date]];
                [dic setObject:datestr forKey:@"TestTime"];


               /* // First Time

                NSUserDefaults *userDefaults ;
                userDefaults = [NSUserDefaults standardUserDefaults];

                if ([userDefaults objectForKey:@"UserWeightDataArray"] == nil)
                {
                    [_valuesArray addObject:dic];
                    [userDefaults setObject:_valuesArray forKey:@"UserWeightDataArray"];
                    [userDefaults synchronize];
                }
                else
                {
                    // second Time

                    [_dateArray addObject:dic];

                    _finalArray = [[_dateArray arrayByAddingObjectsFromArray:[[NSUserDefaults standardUserDefaults] objectForKey:@"UserWeightDataArray"]] mutableCopy];

                    [userDefaults setObject:_finalArray forKey:@"UserWeightDataArray"];
                    [userDefaults synchronize];
                }
                */

             height = [[[MySingleton sharedSingleton].nowuserinfo valueForKey:@"Height"] intValue];
                float bmi = weightdata/((height/100.0f)*(height/100.0f));

                _bmiDataLabel.text = [[NSString alloc] initWithFormat:@"%.1f",bmi];

                NSLog(@"_weightDataLabel.text %@", _weightDataLabel.text);
                [self uploadDeviceInformationToServer:height weight:[[NSString alloc]initWithFormat:@"%.1f",weightdata]];




                NSThread* myThread2 = [[NSThread alloc] initWithTarget:self selector:@selector(uploadWeightData:)object:dic];
                [myThread2 start];

                NSThread* myThread3 = [[NSThread alloc] initWithTarget:self selector:@selector(getAdviceByWeightData:)object:dic];
                [myThread3 start];

                NSThread* myThread = [[NSThread alloc] initWithTarget:self selector:@selector(sendCloseCmd)object:nil];
                [myThread start];

            }
        }
    }
    else
    {
        _lastWeightData = 0;
        Byte weightHigh = 0;
        if(byte[1] >= 0xc0)
        {
            weightHigh = byte[1] - 0xc0;
        }
        else if(byte[1] >= 0x80)
        {
            weightHigh = byte[1] - 0x80;
        }
        else if(byte[1]>= 0x40)
        {
            weightHigh = byte[1] - 0x40;
        }

        float weightdata = (float)(weightHigh * 256 + byte[2])/10;
        NSUserDefaults *prefers = [NSUserDefaults standardUserDefaults];
        NSLog(@"data is %@",[prefers objectForKey:@"units"]);
        if([[prefers objectForKey:@"units"] isEqualToString:@"ft"])
        {

            double temp=[UnitParse convertKgToLb:weightdata];
            double temp1=[UnitParse convertLbToKg:weightdata];
            NSString *weight = [[NSString alloc]initWithFormat:@"%.1f",temp];
            NSLog(@"weight in if .... %@ and lb is %.1f and kg %.1f",weight,temp,temp1);
            _weightDataLabel.text = [[NSString alloc] initWithFormat:@"%@",weight];

        }
        else
        {

            double temp=[UnitParse convertKgToLb:weightdata];
            double temp1=[UnitParse convertLbToKg:weightdata];
             NSLog(@"weight in if .... %f and lb is %.1f and kg %.1f",weightdata,temp,temp1);
            NSString *weight = [[NSString alloc]initWithFormat:@"%.1f",temp1];
            NSLog(@"weight in else .... %@",weight);
            _weightDataLabel.text = [[NSString alloc] initWithFormat:@"%@",weight];
        }



       // NSString *weight = [[NSString alloc]initWithFormat:@"%.1f",[UnitParse convertKgToLb:weightdata]];
       // _weightDataLabel.text = [[NSString alloc] initWithFormat:@"%@",weight];
    }


    // Have we got everything we need?
    if ([stringFromData isEqualToString:@"EOM"]) {

        // We have, so show the data,
        //[self.textview setText:[[NSString alloc] initWithData:self.data encoding:NSUTF8StringEncoding]];
        NSLog(@"GetDataValue : %@",[[NSString alloc] initWithData:self.data encoding:NSUTF8StringEncoding]);
        // Cancel our subscription to the characteristic
        [peripheral setNotifyValue:NO forCharacteristic:characteristic];

        // and disconnect from the peripehral
        [self.centralManager cancelPeripheralConnection:peripheral];
    }

}

字节数据的输出是:

Receive byte:14 byte data is 0xe 
Receive byte:176 byte data is 0xb0 
Receive byte:4 byte data is 0x4 
Receive byte:223 byte data is 0xdf 
Receive byte:7 byte data is 0x7 
Receive byte:1 byte data is 0x1 
Receive byte:1 byte data is 0x1 
Receive byte:23 byte data is 0x17 
Receive byte:48 byte data is 0x30 
Receive byte:17 byte data is 0x11 
Receive byte:1 byte data is 0x1

1 个答案:

答案 0 :(得分:1)

使用此代码读取重量或心率或温度的字节数据。

    Lol is the nsdata object.
    const uint8_t *reportData = [lol bytes];
    uint16_t bpm = (uint16_t)reportData;

    CGFloat weightdata = 0;
    if ((reportData[1] & 0x01) == 0)
    {
        /* uint8 bpm */
        NSLog(@"if reportData is %d",reportData[1]);
        bpm = CFSwapInt16LittleToHost(*(uint16_t *)(&reportData[1]));
        NSLog(@"if bpm data is %d",bpm);
        weightdata = bpm/200.0;
    }
    else
    {
        /* uint16 bpm */
        NSLog(@"reportData is %d",reportData[1]);
        bpm = CFSwapInt16LittleToHost(*(uint16_t *)(&reportData[1]));
        NSLog(@"bpm data is %d",bpm);
        weightdata = bpm/200.0;

    }