2016-02-04 1 views
1

Я пытаюсь прочитать данные с устройства BLE, получая данные от метода делегирования - (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error.iOS чтение данных из bluetooth 4.2 Устройство BLE

Я читаю данные из объекта CBCharacteristic, используя свойство value.

Это возвращает NSData. Я преобразовал это NSData в Bytes.

Как рассчитать вес из данных байтов ?. По этому коду я не получаю точного значения.

Вот 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 
+0

Какие байты вы получаете и какое значение представляют эти байты? – Paulw11

+0

Вот мой код –

+0

NSData * temp = character.value; Byte * byte = (Byte *) [temp bytes]; вывода данных байт: Получить байты: 14 байт данных 0xE Получить байты: 176 байт данных 0xb0 Получить байты: 4 байта данных 0x4 Получить байты: 223 байт данных 0xDF Получить байты: 7 байт данных 0x7 Получить байт: 1 байт данных 0x1 Получить байт: 1 байт данных 0x1 Получить байт: 23 байт данных 0x17 Получить байт: 48 байт данных 0x30 Получить байт: 17 байт данных 0x11 Получать байт: 1 байт данных 0x1 –

ответ

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; 

    } 
+0

это нормально работает для фунтов, но не для KG –

Смежные вопросы