如何解码BLE特征值?

时间:2018-01-27 01:34:32

标签: ios swift core-bluetooth

didDiscoverCharacteristicsFor,我致电peripheral.readValue( for: characteristic)

didUpdateValueFor中,我读取特征值,输出为1字节。

所以我使用字节串起来。

var str = String( data: characteristic.value! , encoding: String.Encoding.utf8) as String!

输出是:

  

可选( “\∪{02}”)。

我想得到“02”。我该怎么做?

1 个答案:

答案 0 :(得分:0)

您需要将CBC特性对象直接传递给您在 didUpdateValueFor 函数中收到的此函数。你将得到一个8位的值。

private func myCharacteristics(from characteristic: CBCharacteristic) -> String {

  guard let characteristicData = characteristic.value,
  let byte = characteristicData.first else { return "Error" }

 switch byte {
  case 0: return "0th bit"
  case 1: return "1st bit"
  case 2: return "2nd bit"
  case 3: return "3rd bit"
  case 4: return "4th bit"
  case 5: return "5th bit"
  case 6: return "6th bit"
  default:
  return "Other"
 }
}

I hope this will help you.