我正在用SWIFT编写一段代码,以便从BLE设备(欧姆龙BP7000)获取数据.我能够与它配对,并获得其他服务并读取数据.但是我无法得到血压的数据,在didUpdateValueFor characteristic:.其他代表的核心蓝牙已经被使用,并正在发挥预期的作用.就在读取/写入当前时间的数据和从血压特性读取数据时,我遇到了问题.如果有人可以张贴一些建议,我应该如何进行将是有帮助的.

func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {
      switch characteristic.uuid {
    
      case batteryLevelCBUUID:
          print("Battery level: \(characteristic.value![0])")
          let valueBattery = characteristic.value?[0]
          batteryLabel.text = "Battery Level =" + " " + String(describing: characteristic.value!      [0]) + "%"
          centerView.isHidden = false
      case currentTimeCBUUID:
          peripheral.readValue(for: characteristic)
          let currentDate = Date()
          //           Write the date and time to the characteristic
          writeCurrentTime(to: characteristic, in: peripheral)
          //          print("\(characteristic.value as Any) gives Current Time String  ")
          if let dateTime = extractDateTime(from: characteristic) {
              print("Date and Time:", dateTime)
          } else {
              print("Unable to extract date and time from the characteristic.")
          }
       case bloodPressureMeasurementCBUUID:
          decodeBloodPressureMeasurementData(from: characteristic)
          print("\(characteristic.value as Any) gives 2A35 ")
       default:
          print("")

}
}

    func peripheral(_ peripheral: CBPeripheral, didWriteValueFor characteristic: CBCharacteristic, error: Error?) {
        if let error = error {
            // Handle write error
            print("Error writing value: \(error.localizedDescription)")
        } else {
            // Handle successful write
            print("Value written successfully")

            // Check if the characteristic supports notifications
            if characteristic.properties.contains(.notify) {
                peripheral.setNotifyValue(true, for: characteristic)
            }
        }
    }


    func writeCurrentTime(to characteristic: CBCharacteristic, in peripheral: CBPeripheral) {
        // Get the current date and time
        let currentDate = Date()
        let calendar = Calendar.current
        var components = calendar.dateComponents([.year, .month, .day, .hour, .minute, .second, .weekday, .nanosecond], from: currentDate)
        
        // Create the value to be written
        var value = Data()
        value.append(Data(bytes: &components.year!, count: 2)) // Year (2 bytes)
        value.append(Data(bytes: "", count: 0))
        value.append(UInt8(components.month!)) // Month (1 byte)
        value.append(UInt8(components.day!)) // Day (1 byte)
        value.append(UInt8(components.hour!)) // Hours (1 byte)
        value.append(UInt8(components.minute!)) // Minutes (1 byte)
        value.append(UInt8(components.second!)) // Seconds (1 byte)
        value.append(UInt8(components.weekday!)) // Day of Week (1 byte)
        value.append(contentsOf: components.nanosecond!.bytes(2)) // Fractions of a second (2 bytes)
        
        // Write the value to the Current Time characteristic
        peripheral.writeValue(value, for: characteristic, type: .withResponse)
    }

    
    func decodeBloodPressureMeasurementData(from characteristic: CBCharacteristic) {
        guard let data = characteristic.value else {
            print("No data available for decoding.")
            return
        }

        let flags = data[0] // Flags byte
        let unitFlags = (flags & 0b00000001) // Bit 0 indicates the unit of blood pressure values
        let timestampFlags = (flags & 0b00000010) // Bit 1 indicates the presence of timestamp

        // Decode systolic, diastolic, and mean arterial pressure values
        let systolicPressure = (data[1] + (data[2] << 8))
        let diastolicPressure = (data[3] + (data[4] << 8))
        let meanArterialPressure = (data[5] + (data[6] << 8))

        // Decode pulse rate value
        let pulseRate = (data[7] + (data[8] << 8))


        // Decode unit of blood pressure values
        let unit: String = (unitFlags != 0) ? "kPa" : "mmHg"

        // Process and use the decoded values as needed
        print("Systolic Pressure: \(systolicPressure) \(unit)")
        print("Diastolic Pressure: \(diastolicPressure) \(unit)")
        print("Mean Arterial Pressure: \(meanArterialPressure) \(unit)")
        print("Pulse Rate: \(pulseRate) bpm")
    }
    


  [1]: https://i.stack.imgur.com/fYaxj.png

推荐答案

我已经找到了这个问题的答案.我使用的是data(),而不是当我使用NSMuableData()时,它开始工作并连接到BLE设备(Omron BP 7000).以下是我使用的答案的代码.

// Define the CurrentTime structure
struct DateAndTime {
    var year: UInt16
    var month: UInt8
    var day: UInt8
    var hours: UInt8
    var minutes: UInt8
    var seconds: UInt8
}

struct CurrentTime {
    var dateData : DateAndTime
    var dayOfWeek: UInt8
    var fractions256: UInt8
    var adjustReason: UInt8
}



func writeCurrentTime(to characteristic: CBCharacteristic, in peripheral: CBPeripheral){
        // Get the current date and time
        let currentDate = Date()
        let calendar = Calendar.current
        let components = calendar.dateComponents([.year, .month, .day, .hour, .minute, .second, .weekday, .nanosecond], from: currentDate)
        // Send the bytes to the BLE device
        let data = NSMutableData()
        
        let time = DateAndTime(year: UInt16(components.year!), month: (UInt8(components.month!) + 1), day: (UInt8(components.day!)), hours: (UInt8(components.hour!)), minutes: (UInt8(components.minute!)), seconds: (UInt8(components.second!)))
        
        
        // Create an instance of CurrentTime with current date and time
        let currentTime = CurrentTime(dateData: time, dayOfWeek: (components.btDayOfWeek), fractions256: UInt8(components.nanosecond! * 256 / Int(NSEC_PER_SEC)), adjustReason: 0)    // Replace with the actual year
        
        // Convert the CurrentTime structure to Data
        let currentTimeData = withUnsafeBytes(of: currentTime) { Data($0) }
        data.append(currentTimeData)
        // Write the value to the Current Time characteristic
        peripheral.writeValue(data as Data, for: characteristic, type: .withResponse)
    }

Ios相关问答推荐

SwiftUI拖动手势和内容拖动时的奇怪行为( skip /卡顿)

UIAlertController的空子类是否可以与`appearance(whenContainedInInstancesOf:)`一起安全使用

检测touch 并忽略其他手势SWIFT SceneKit

仅更改 AttributedString 的字符串(例如 UIButton 配置 attributeTitle)

iOS设备网页自动化中,在向字段发送文本后未启用按钮

UIView 倒置旋转时的zoom 问题

Flutter IOS 构建错误 - 在签名和功能编辑器中 Select 一个开发团队.

添加到单个自定义视图时,Swiftui 项目会在所有视图中重复

通过隐藏和显示视图在 iMessage 应用程序中使用不同的视图

使用 @MainActor 更新 UI 的适当策略是什么?

Flutter:无法构建 iOS 应用程序ARCHIVE FAILED,为设备归档时遇到错误

如何判断 `NSManagedObject` 是否已被删除?

ARKit vs. ARCore vs. Vuforia vs. D'Fusion Mobile vs. Layar SDK

使用导航控制器在prepareForSegue中设置数据

用 PC 调试 ipad safari

每个版本的 iOS 都附带什么版本的移动 Safari?

如何缩小 UIImage 并使其同时变得清晰/锐利而不是模糊?

什么是伞头?

如果已安装,则重定向到应用程序,否则重定向到 App Store

UITextView 内容插图