从BLE获取字符串

问题描述 投票:0回答:2

您好,我是 swift 的初学者,我正在尝试制作一个应用程序,将一个 BLE 与极心率进行通信,我在从characteristic.value 生成的数据结构中获取正确的信息时遇到问题,我真的有一个问题将其从 uint8 转换为更简单的类型,例如 int 或字符串。

她是我的代码:

func peripheral(_ peripheral: CBPeripheral, didUpdateValueForCharacteristic characteristic: CBCharacteristic, error: NSError?) {

    if characteristic.uuid == POLARH7_HRM_MEASUREMENT_CHARACTERISTIC_UUID {
        print("Get the new heart BPM : ", terminator:"")

        var wavelength: UInt16?
        if let data = characteristic.value {
            var bytes = Array(repeating: 0 as UInt8, count:(characteristic.value?.count)!/MemoryLayout<UInt8>.size)

            data.copyBytes(to: &bytes, count:data.count)
            let data16 = bytes.map { UInt16($0) }
            wavelength = 256 * data16[1] + data16[0]

        }
        print("W : ")
        print(wavelength)
    }

    if characteristic.uuid == POLARH7_HRM_BODY_LOCATION_CHARACTERISTIC_UUID {
        print("Get the new sensor location", terminator:"")
        print(characteristic.value)
        //let data = NSData(data: characteristic.value as! Data)

    }

    if characteristic.uuid == POLARH7_HRM_MANUFACTURER_NAME_CHARACTERISTIC_UUID {
        print("Get the new name", terminator:"")
        print(characteristic.value)
    }

}

我尝试了很多方法,但我对 swift 很陌生,而且 Swift 3 并不容易,因为这种语言每年都会有更新,所以发现的最多提示是 Objective-C 或 Swift 2。 就像这个例子:

    // Instance method to get the manufacturer name of the device
- (void) getManufacturerName:(CBCharacteristic *)characteristic
{
    NSString *manufacturerName = [[NSString alloc] initWithData:characteristic.value encoding:NSUTF8StringEncoding];  // 1
    self.manufacturer = [NSString stringWithFormat:@"Manufacturer: %@", manufacturerName];    // 2
    return;
}

    - (void) getHeartBPMData:(CBCharacteristic *)characteristic error:(NSError *)error
{
    // Get the Heart Rate Monitor BPM
    NSData *data = [characteristic value];      // 1
    const uint8_t *reportData = [data bytes];
    uint16_t bpm = 0;

    if ((reportData[0] & 0x01) == 0) {          // 2
        // Retrieve the BPM value for the Heart Rate Monitor
        bpm = reportData[1];
    }
    else {
        bpm = CFSwapInt16LittleToHost(*(uint16_t *)(&reportData[1]));  // 3
    }
    // Display the heart rate value to the UI if no error occurred
    if( (characteristic.value)  || !error ) {   // 4
        self.heartRate = bpm;
        self.heartRateBPM.text = [NSString stringWithFormat:@"%i bpm", bpm];
        self.heartRateBPM.font = [UIFont fontWithName:@"Futura-CondensedMedium" size:28];
        [self doHeartBeat];
        self.pulseTimer = [NSTimer scheduledTimerWithTimeInterval:(60. / self.heartRate) target:self selector:@selector(doHeartBeat) userInfo:nil repeats:NO];
    }
    return;
}

提前致谢

ios swift bluetooth-lowenergy nsdata
2个回答
2
投票

从 BLE 设备发送的数据通常采用 unicode 格式,因此您需要将这些 unicode 值转换为您需要的任何值。

这是将其转换为字符串的示例:

// Convert byte to unicode string
let unicodeString = String(data: characteristic.value!, encoding: String.Encoding.utf8)

// Initialize value
var value: String? = nil

// Convert unicode to actual value
for element in unicodeString!.unicodeScalars {
    value = "\(element.value)"
}

// If value exists
if let value = value {
    // Do something with the value
}

1
投票

也许其他人之后也在寻找相同的答案。这是我获取 int 的方法。

let data = characteristic.value
let count = (data?.count)! / MemoryLayout<UInt8>.size
var array = [UInt8](repeating: 0, count: count)
data?.copyBytes(to: &array, count:count * MemoryLayout<UInt8>.size)
print("Get the new heart BPM : ", terminator : "")
if ((array[0] & 0x01) == 0) {
    let bpm = array[1]
    let bpmInt = Int(bpm)
    print(bpmInt)
}
© www.soinside.com 2019 - 2024. All rights reserved.